package com.itwhy.controller;

import cn.hutool.core.bean.BeanUtil;
import com.itwhy.domain.dto.PageDTO;
import com.itwhy.domain.dto.UserFormDTO;
import com.itwhy.domain.po.User;
import com.itwhy.domain.query.UserQuery;
import com.itwhy.domain.vo.UserVO;
import com.itwhy.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 王海云
 * @version 1.0.0
 * ClassName UserController
 * DateTime 2023/11/21 16:35
 */
@Api(tags = "用户管理接口")
@RestController
@RequiredArgsConstructor // 采用这种方式注入更好
@RequestMapping("/users")
public class UserController {
    private final UserService userService;
    @ApiOperation("新增用户接口")
    @PostMapping
    public void saveUser(@RequestBody UserFormDTO userDTO) {
        // 1.把DTO拷贝到PO
        User user = BeanUtil.copyProperties(userDTO, User.class); // hutool依赖的作用体现
        // 2.新增
        userService.save(user);
    }

    @ApiOperation("删除用户接口")
    @DeleteMapping("/{id}")
    public void deleteUser(@ApiParam("用户ID") @PathVariable Long id) {
        // 1.删除
        userService.removeById(id);
    }

    @ApiOperation("根据id查询用户接口")
    @GetMapping("/{id}")
    public UserVO queryUserById(@ApiParam("用户ID") @PathVariable Long id) {
        return userService.queryUserAndAddressById(id);
    }

    @ApiOperation("根据id批量查询用户接口")
    @GetMapping
    public List<UserVO> queryUsersByIds(@ApiParam("用户ID集合") @RequestParam List<Long> ids) {
        return userService.queryUserAndAddressByIds(ids);
    }

    @ApiOperation("根据id扣减余额")
    @GetMapping("{id}/deduction/{money}")
    public void deductMoneyById(@ApiParam("用户ID") @PathVariable Long id,
                                @ApiParam("扣减金额") @PathVariable Integer money) {
        userService.updateBalanceById(id, money);
    }

    @ApiOperation("条件分页查询")
    @GetMapping("list")
    public PageDTO<UserVO> queryUsers(UserQuery userQuery) {
        return userService.queryUsersPage(userQuery);
    }
}
